package login

import AuthRepository
import BaseViewModel
import LoadingStatus
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import login.models.LoginEvent
import login.models.LoginViewState

class LoginViewModel(
    private val repository: AuthRepository
) : BaseViewModel<LoginViewState, LoginEvent>(
    initialState = LoginViewState()
) {
    override fun obtainEvent(event: LoginEvent) {
        when (event) {
            is LoginEvent.UsernameChanged -> {
                updateState { it.copy(username = event.username) }
            }

            is LoginEvent.PasswordChanged -> {
                updateState { it.copy(password = event.password) }
            }

            is LoginEvent.LoginClicked -> {
                updateState { it.copy(loadingStatus = LoadingStatus.Loading) }
                viewModelScope.launch {
                    repository.login(viewState.username, viewState.password)
                        .onSuccess { updateState { it.copy(loadingStatus = LoadingStatus.FullyLoad) } }
                        .onFailure { t ->
                            updateState {
                                it.copy(
                                    loadingStatus = LoadingStatus.Error(
                                        t.message
                                    )
                                )
                            }
                        }
                }
            }
        }
    }
}